package com.qing.common_result.result;


import com.qing.common_result.result.CommonFinal;
import com.qing.common_result.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 上面代码就是判断是否需要返回值包装，如果需要就直接包装。这里我们只处理了正常成功的包装，如果方法体报异常怎么办？处理异常也比较简单，只要判断body是否为异常类。
 */
@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {


	//是否请求，包含了包装，注解，标记，没有就直接返回，不要重写返回体
	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
//        log.info("判断是否打有标记 --------------------------");
		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = sra.getRequest();
		//判断请求是否包含标记
		ResponseResult responseResult = (ResponseResult) request.getAttribute(CommonFinal.RESPONSE_RESULT_ANN);
		return responseResult == null ? false : true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        log.info("进入返回体 重写格式 处理中 --------------------------");
//        log.info(JSONObject.toJSONString(body, SerializerFeature.PrettyFormat));
		return Result.success(body);
	}


}
